import React,{useEffect, useState, useRef} from 'react'
import { Row, Col, Card, List, Avatar, Drawer } from 'antd'
import { NavLink } from 'react-router-dom';
import { EditOutlined, EllipsisOutlined, PieChartOutlined } from '@ant-design/icons';
import axios from 'axios'
import * as Echarts from 'echarts'
import _ from 'lodash'

// 将 Meta 从 Card 组件中解构出来
const { Meta } = Card

export default function Home() {
  
  // 从本地存储中将当前用户的数据解构出来
  const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem("token"))
  
  // 创建存储用户最常浏览数据的属性
  const [viewList, setviewList] = useState([])

  // 创建存储用户点赞最多数据的属性
  const [starList, setstarList] = useState([])

  // 控制Drawer抽屉组件的隐藏显示
  const [open, setOpen] = useState(false);

  // 存储数据可视化视图需要的数据
  const [allList, setallList] = useState([])

  // 获取数据可视化视图需要的数据
  useEffect(() => {
    axios.get('/news?publishState=2&_expand=category').then((res) => {
      console.log(res.data)
      renderBarView(_.groupBy(res.data, item => item.category.label))
      setallList(res.data)
    })
  }, [])

  // 获取用户最常浏览的数据
  useEffect(() => {
    axios.get('/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6', {
    }).then((res) => {
      setviewList(res.data)
    })
    return () => {
      // 清除resize事件
      window.onresize = null
    }
  }, [])
  
   // 获取用户点赞最多的数据
   useEffect(() => {
    axios.get('/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6', {
    }).then((res) => {
      setstarList(res.data)
    })
  }, [])


  // 用于获取具有柱状图数据可视化效果的div标签的实例
  const barRef = useRef()

  // 初始化echarts柱状图实例
  const renderBarView = (obj) => {
    // 基于准备好的dom，初始化echarts实例
    var myChart = Echarts.init(barRef.current);

    // 指定图表的配置项和数据
    var option = {
      title: {
        text: '新闻分类图示'
      },
      tooltip: {},
      legend: {
        data: ['数量']
      },
      xAxis: {
        data: Object.keys(obj),
        axisLabel: {
          rotate: "45",
          interval: 0
        }
      },
      yAxis: {
        minInterval: 1
      },
      series: [
        {
          name: '数量',
          type: 'bar',
          data: Object.values(obj).map(item => item.length)
        }
      ]
    };
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);

    // 柱状图宽度自适应
    window.onresize = () => {
      // 当前页面窗口的尺度变化的时候，调用下面这个函数
      myChart.resize()
    }
  }

  
  // 点击抽屉Drawer组件中的关闭按钮的事件回调
  const onClose = () => {
    setOpen(false);
  }

  // 点击卡片Card组件中的饼状按钮的事件回调
  const showDrawer = () => {
    setOpen(true);
  }

  
  // 用于获取具有饼状图数据可视化效果的div标签的实例
  const pieRef = useRef()
  
  const [pieChart, setpieChart] = useState(null)

  // 初始化echarts饼状图实例
  const renderPieView = () => {
    // 数据处理
    var currentList = allList.filter(item => item.author === username)
    var groupObj = _.groupBy(currentList, item => item.category.label)
    var list = []
    for (var i in groupObj) {
      list.push({
        name: i,
        value: groupObj[i].length
      })
    }

    var myChart;
    if (!pieChart) {
      myChart = Echarts.init(pieRef.current);
      setpieChart(myChart)
    } else {
      myChart = pieChart
    }
    var option;

    option = {
      title: {
        text: '当前用户的新闻分类图示',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '发布数量',
          type: 'pie',
          radius: '50%',
          data: list,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };

    option && myChart.setOption(option);

  }

  return (
    <div className="site-card-wrapper">
      <Row gutter={16}>
        <Col span={8}>
          <Card title="用户最常浏览" bordered={true}>
            <List
              size="small"
              dataSource={viewList}
              renderItem={
                item => {
                return <List.Item><NavLink to={`/news-manage/preview/${item.id}`}>{item.title}</NavLink></List.Item>}
              }
            />
          </Card>
        </Col>

        <Col span={8}>
          <Card title="用户点赞最多" bordered={true}>
            <List
                size="small"
                // bordered
                dataSource={starList}
                renderItem={
                  item => {
                  return <List.Item><NavLink to={`/news-manage/preview/${item.id}`}>{item.title}</NavLink></List.Item>}
                }
            />
          </Card>
        </Col>

        <Col span={8}>
          <Card
            cover={
              <img
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <PieChartOutlined 
                key="setting" 
                onClick={() => {
                  showDrawer()
                  setTimeout(() => {
                    renderPieView()
                  }, 0)
                }} 
              />,
              <EditOutlined key="edit" />,
              <EllipsisOutlined key="ellipsis" />,
            ]}
          >
            <Meta
              avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
              title={username}
              description={
                <div>
                  <b>{region ? region : '全球'}</b>
                  <span style={{ paddingLeft: '30px' }}>
                    {roleName}
                  </span>
                </div>
              }
            />
          </Card>
        </Col>
      </Row>

      {/* 抽屉组件 */}
      <Drawer
        title="个人新闻分类"
        placement="right"
        width="500px"
        // 允许关闭
        closeable={true}
        // 当前抽屉组件隐藏的时候触发这个事件
        onClose={onClose}
        open={open}
      >
        {/* 饼状图 */}
        <div ref={pieRef} style={{ height: "600px" }}></div>
      </Drawer>

      {/* 柱状图 */}
      <div ref={barRef} style={{ height: "400px" }}></div>
    </div>
  )
}
